import React, { useState, useEffect } from 'react';
import './App.css';
import TaskList from './components/TaskList';
import PromptForm from './components/PromptForm';
import PromptInput from './components/PromptInput';

function App() {
  const [showPromptForm, setShowPromptForm] = useState(false);
  
  // 对任务按 TaskID 排序的函数
  const sortTasksByID = (tasks: any[]) => {
    return [...tasks].sort((a, b) => {
      // 提取数字部分进行比较
      const idA = parseInt(a.TaskID.replace('TASK', ''));
      const idB = parseInt(b.TaskID.replace('TASK', ''));
      return idA - idB;
    });
  };

  // Mock data for pending tasks with different statuses
  const [pendingTasks, setPendingTasks] = useState([
    { TaskID: 'TASK002', productName: 'Product A', status: '待处理' },
    { TaskID: 'TASK001', productName: 'Product B', status: '待处理' },
    { TaskID: 'TASK005', productName: 'Product C', status: '处理中' },
    { TaskID: 'TASK004', productName: 'Product D', status: '处理中' },
    { TaskID: 'TASK007', productName: 'Product A', status: '待处理' },
    { TaskID: 'TASK009', productName: 'Product B', status: '待处理' },
    { TaskID: 'TASK008', productName: 'Product C', status: '处理中' },
    { TaskID: 'TASK006', productName: 'Product D', status: '处理中' }
  ]);
  
  // Mock data for completed tasks
  const [completedTasks, setCompletedTasks] = useState([
    { TaskID: 'TASK005', productName: 'Product E', status: '已完成' },
    { TaskID: 'TASK006', productName: 'Product F', status: '已完成' },
    { TaskID: 'TASK007', productName: 'Product G', status: '已完成' }
  ]);

  // 初始化时对任务进行排序
  useEffect(() => {
    setPendingTasks(prevTasks => sortTasksByID(prevTasks));
    setCompletedTasks(prevTasks => sortTasksByID(prevTasks));
  }, []);

  const handleTaskUpdate = (taskId: string, actionType: number) => {
    // 根据操作类型处理任务
    switch (actionType) {
      case 1: // 终止
        // 找到要终止的任务
        const taskToTerminate = pendingTasks.find(task => task.TaskID === taskId);
        if (taskToTerminate) {
          // 从待处理任务列表中移除任务
          setPendingTasks(prevTasks => {
            const updatedTasks = prevTasks.filter(task => task.TaskID !== taskId);
            return sortTasksByID(updatedTasks);
          });
          
          // 将任务添加到已完成列表，标记为已终止
          setCompletedTasks(prevTasks => {
            const terminatedTask = {
              ...taskToTerminate,
              status: '已完成',
              isTerminated: true, // 添加标记以区分终止的任务
              canContinue: true // 添加标记表示可以继续处理
            };
            const updatedTasks = [...prevTasks, terminatedTask];
            return sortTasksByID(updatedTasks);
          });
        }
        break;
      case 3: // 继续处理
        // 找到要继续处理的任务
        const taskToContinue = completedTasks.find(task => task.TaskID === taskId);
        if (taskToContinue) {
          // 从完成列表中移除任务
          setCompletedTasks(prevTasks => {
            const updatedTasks = prevTasks.filter(task => task.TaskID !== taskId);
            return sortTasksByID(updatedTasks);
          });
          
          // 将任务添加到待处理列表
          setPendingTasks(prevTasks => {
            const continuedTask = {
              ...taskToContinue,
              status: '处理中',
              isTerminated: false,
              canContinue: false
            };
            const updatedTasks = [...prevTasks, continuedTask];
            return sortTasksByID(updatedTasks);
          });
        }
        break;
      case 0: // 取消
      case 2: // 删除
        // 从待处理任务列表中移除任务，并保持排序
        setPendingTasks(prevTasks => {
          const updatedTasks = prevTasks.filter(task => task.TaskID !== taskId);
          return sortTasksByID(updatedTasks);
        });
        break;
      default:
        break;
    }
  };

  // 模拟接收新任务数据的函数
  const handleNewTasksData = (newTasks: any[]) => {
    setPendingTasks(prevTasks => {
      const combinedTasks = [...prevTasks, ...newTasks];
      return sortTasksByID(combinedTasks);
    });
  };

  const handlePromptSubmit = (prompt: string) => {
    console.log('Submitted prompt:', prompt);
    // Add logic to handle the prompt submission
  };

  const handleFormSubmit = (formData: any) => {
    console.log('Form data submitted:', formData);
    setShowPromptForm(false);
    // Add logic to handle the form submission
  };

  const openPromptForm = () => {
    setShowPromptForm(true);
  };

  return (
    <div className="App">
      <div className="app-container">
        <div className="task-lists">
          <div className="task-column">
            <TaskList 
              title="任务列表" 
              tasks={pendingTasks} 
              onTaskUpdate={handleTaskUpdate}
            />
          </div>
          <div className="task-column">
            <TaskList 
              title="完成列表" 
              tasks={completedTasks} 
              showOption={true}
              onTaskUpdate={handleTaskUpdate}
            />
          </div>
        </div>
        
        <div className="prompt-section">
          <PromptInput 
            onSubmit={handlePromptSubmit} 
            onOpenForm={openPromptForm}
          />
        </div>
        
        {showPromptForm && (
          <PromptForm 
            onClose={() => setShowPromptForm(false)} 
            onSubmit={handleFormSubmit} 
          />
        )}
      </div>
    </div>
  );
}

export default App;
